<!--
 * @LastEditTime: 2023-11-24 10:50:43
 * @FilePath: \bdcar-net\src\views\comlbs\equipmentManagement\index.vue
 * @Description: 设备管理 
-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item :label="v.name" :prop="v.prop" v-for="v in searchItems"
        :style="{ width: v.type == 'dateTime' ? '448px' : '' }">
        <el-input v-if="v.type == 'input'" v-model="queryParams[v.prop]" :placeholder="'请输入' + v.name" clearable
          @keyup.enter="handleQuery" />
        <el-tree-select v-else-if="v.type == 'treeSelect'" v-model="queryParams[v.prop]" :placeholder="'请选择' + v.name"
          clearable :data="sel_option[v.prop]" :expand-on-click-node="false" :render-after-expand="false"
          @change="handleQuery" check-strictly :props="{ label: 'label' }" node-key="id" filterable />
        <el-date-picker v-else-if="v.type == 'dateTime'" v-model="queryParams[v.prop]" value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange" :default-time="[new Date(2000, 1, 1, 0, 0, 0),
          new Date(2000, 2, 1, 23, 59, 59),]" range-separator="-" start-placeholder="开始时间"
          end-placeholder="结束时间"></el-date-picker>
        <el-date-picker v-else-if="v.type == 'date'" v-model="queryParams[v.prop]" value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="[new Date(2000, 1, 1, 0, 0, 0),
          new Date(2000, 2, 1, 23, 59, 59),]" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期"></el-date-picker>
        <el-select v-else-if="v.type == 'select' && v.prop != 'checkStatus'" v-model="queryParams[v.prop]" clearable
          filterable :placeholder="'请输入' + v.name" @change="handleQuery">
          <el-option v-for="item in sel_option[v.prop]" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select v-else-if="v.type == 'select' && v.prop == 'checkStatus'" v-model="queryParams[v.prop]" clearable
          filterable :placeholder="'请输入' + v.name" @change="handleQuery">
          <el-option v-for="item in sel_option[v.prop]" :key="item.value" :label="item.label" :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['comlbs:equipmentManagement:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['comlbs:equipmentManagement:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['comlbs:equipmentManagement:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Upload" @click="handleImport"
          v-hasPermi="['comlbs:equipmentManagement:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Box" :disabled="multiple" @click="handleCheck"
          v-hasPermi="['comlbs:equipmentManagement:selfCheck']">自检</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Switch" :disabled="multiple" @click="handleSwitch"
          v-hasPermi="['comlbs:equipmentManagement:transfer']">转移</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table highlight-current-row v-loading="loading" :data="equipmentManagementList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column :label="v.name" align="left" :prop="v.prop" v-for="v in tableItems" :width="v.width">
        <template #header>
          {{ v.name }}
          <el-tooltip effect="dark" content="每十分钟更新一次" placement="top-start" v-if="v.prop == 'accountStatus'">
            <el-icon style="position: relative;top:2px">
              <InfoFilled />
            </el-icon>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag v-if="v.type == 'dict'" :options="sel_option[v.prop]" :value="scope.row[v.prop]" />
          <img v-else-if="v.prop == 'objIcon' && scope.row[v.prop]"
            :src="myRequire('equipment/' + scope.row[v.prop] + '.png')" />
          <span v-else-if="v.prop == 'deviceId'">
            <el-tooltip effect="dark" :content="scope.row.checkDetail" placement="top-start" v-if="scope.row.checkDetail">
              <img :src="myRequire('table/' + statusImg[scope.row.checkStatus])" />
            </el-tooltip>
            {{ scope.row[v.prop] }}
          </span>
          <span v-else>{{ scope.row[v.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="260">
        <template #default="scope">
          <el-button link type="primary" icon="Document" @click="handleDetail(scope.row)"
            v-hasPermi="['comlbs:equipmentManagement:edit']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['comlbs:equipmentManagement:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['comlbs:equipmentManagement:remove']">删除</el-button>
          <el-button link type="primary" @click="handleIssue(scope.row)">下发</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" v-model="open" :width="setPopWidth(showWhich)" :destroy-on-close="true"
      :class="{ skyForm: showWhich != 'import' && showWhich != 'switch' }">
      <importInfo v-if="showWhich == 'import'" :sel_option="sel_option" ref="formInfo" :disabled="disabled">
      </importInfo>
      <switchInfo v-else-if="showWhich == 'switch'" :sel_option="sel_option" ref="formInfo" :disabled="disabled">
      </switchInfo>
      <updateInfo v-else :showWhich="showWhich" :form="form" :sel_option="sel_option" ref="formInfo" :disabled="disabled">
      </updateInfo>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!disabled">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 下发 -->
    <el-dialog title="下发" v-model="issueOpen" width="60%" append-to-body>
      <div class="body" style="height:500px">
        <el-tabs v-model="activeName" @tab-change="tabChangeIssue">
          <el-tab-pane label="下发" name="first"></el-tab-pane>
          <el-tab-pane label="下发记录" name="second"></el-tab-pane>
        </el-tabs>
        <div v-show="activeName == 'first'" class="issue-dom">
          <div class="unsetSearch">
            <el-input clearable v-model.trim="queryIssue.name" placeholder="姓名" class="search-input"></el-input>
            <el-tree-select v-model="queryIssue.companyId" placeholder="所属公司" clearable :data="sel_option.companyId"
              :expand-on-click-node="false" :render-after-expand="false" @change="getIssueTableData" check-strictly
              :props="{ label: 'label' }" node-key="id" filterable />
            <el-button type="primary" icon="Search" class="search-btn" @click="getIssueTableData">搜索</el-button>
          </div>
          <div class="dialog-table">
            <div class="paging-table" style="height: 100%;">
              <el-table highlight-current-row :data="tableIssueData" @selection-change="handleIssueSelectionChange"
                ref="bindIssueRef" :header-cell-style="{ 'text-align': 'left' }" :cell-style="{ 'text-align': 'left' }"
                height="100%">
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column :prop="v.prop" :label="v.name" v-for="v in tableIssueItems" :key="v.prop"
                  show-overflow-tooltip> </el-table-column>
              </el-table>
            </div>
          </div>
          <div class="dialog-footer">
            <el-button type="primary" @click="handIssueSubmit">确 定</el-button>
            <el-button @click="handleClose">取 消</el-button>
          </div>
        </div>
        <div v-show="activeName == 'second'" class="issue-dom">
          <div class="unsetSearch">
            <div style="width: 400px;">
              <el-date-picker v-model="queryIssueTime" clearable value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),]" range-separator="-" start-placeholder="开始时间"
                end-placeholder="结束时间"></el-date-picker>
            </div>
            <el-button type="primary" icon="Search" class="search-btn" @click="getIssueRecordData">搜索</el-button>
          </div>
          <div class="dialog-table">
            <div class="paging-table" style="height: 100%;">
              <el-table highlight-current-row :data="issueRecordData" :header-cell-style="{ 'text-align': 'left' }"
                :cell-style="{ 'text-align': 'left' }" height="100%">
                <el-table-column :prop="v.prop" :label="v.name" v-for="v in issueRecordItems" :key="v.prop"
                  :width="v.width" show-overflow-tooltip>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="EquipmentManagement">
import dayjs from "dayjs"
import request from '@/utils/request'
import updateInfo from './updateInfo'
import switchInfo from './switchInfo'
import importInfo from './importInfo'
import { ElLoading } from 'element-plus'
import { listEquipmentManagement, delEquipmentManagement, addEquipmentManagement, updateEquipmentManagement } from "@/api/comlbs/equipmentManagement";
const { proxy } = getCurrentInstance();
import { treeDept } from "@/api/system/dept";
const equipmentManagementList = ref([]);
const open = ref(false);
const disabled = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const showWhich = ref("");
const formInfo = ref(null);
const searchItems = ref([
  { name: '监管类型', prop: "objType", type: 'select' },
  { name: '设备名称', prop: "numberPlate", type: 'input' },
  { name: '设备号', prop: "deviceId", type: 'input' },
  { name: '所属公司', prop: "companyId", type: 'treeSelect' },
  { name: '自检状态', prop: "checkStatus", type: 'select' },
  { name: 'SIM卡状态', prop: "accountStatus", type: 'select' },
  { name: '入网时间', prop: "time", type: 'dateTime' },
]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 15,
    time: [],
  }
});
const statusImg = ref({
  0: "red.png", //未自检
  1: "green.png",//自检通过
  2: "red.png",//自检未通过
  3: "gray.png",//离线
  4: "red.png",//设备未连接网关
})
const tableItems = ref([
  { name: '设备图标', prop: "objIcon", width: '80' },
  { name: '监管类型', prop: "objType", width: '80', type: 'dict' },
  { name: '设备名称', prop: "numberPlate" },
  { name: '设备号', prop: "deviceId" },
  { name: 'SIM卡号', prop: "simId", width: '185' },
  { name: 'SIM卡状态', prop: "accountStatus", width: '110', type: 'dict' },
  { name: '所属公司', prop: "companyName" },
  { name: '备注', prop: 'remark' },
  { name: '入网时间', prop: "activateTime", width: '160' },
  { name: '创建时间', prop: "createTime", width: '160' },
])
function myRequire(str) {
  return new URL(`../../../assets/img/${str}`, import.meta.url).href
}
const sel_option = ref({});

let dictList = tableItems.value.filter(v => v.type == 'dict').map(v => v.prop);
sel_option.value = proxy.useDict.apply(this, [...dictList, "checkStatus", "deviceModel", "channels"]);
proxy.setDataByDictType(sel_option.value, 'sys_user_sex', 'objSex');
const { queryParams, form } = toRefs(data);
treeDept().then(res => {
  sel_option.value.companyId = ref(res.data)
})

// 下发
let multipleIssueSelection = []
const issueOpen = ref(false)
const activeName = ref('first')
const queryIssue = ref({})
const tableIssueData = ref([])
const tableIssueItems = ref([
  { name: '姓名', prop: "name" },
  { name: '所属公司', prop: "companyName" },
  { name: '联系电话', prop: "contactNumber" },
  { name: '年龄', prop: "age" }
])
const queryIssueTime = ref([])
const issueRecordData = ref([])
const issueRecordItems = ref([
  { name: '设备名称', prop: "vehicleNum" },
  { name: '设备号', prop: "deviceNo" },
  { name: '发送状态', prop: "statusName" },
  { name: '下发结果', prop: "responseValue", width: 200 },
  { name: '下发人', prop: "createUserName" },
  { name: '下发时间', prop: "createTime", width: 200 },
  { name: '原因', prop: "failReason" }
])

/** 查询设备管理列表 */
function getList() {
  loading.value = true;
  const { companyId, objType, numberPlate, deviceId, accountStatus, pageSize, pageNum } = queryParams.value
  let param = { companyId, objType, numberPlate, deviceId, accountStatus, pageSize, pageNum };
  param.activateStartTime = queryParams.value.time?.[0]
  param.activateEndTime = queryParams.value.time?.[1]
  param.checkDetail = queryParams.value.checkStatus
  listEquipmentManagement(param).then(response => {
    equipmentManagementList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 设置pop的宽度
function setPopWidth(param) {
  let _hash = {
    import: '400px',
    switch: '400px',
  }
  return _hash[param] ?? '800px'
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {};
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.equipmentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  disabled.value = false;
  open.value = true;
  title.value = "添加设备";
  showWhich.value = 'add';
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  disabled.value = false;
  form.value = row;
  showWhich.value = 'edit';
  open.value = true;
  title.value = "修改设备";
}

/** 详情按钮操作 */
function handleDetail(row) {
  handleUpdate(row);
  title.value = "设备详情";
  disabled.value = true;
}

/** 导入操作 */
function handleImport() {
  open.value = true;
  title.value = "导入数据";
  showWhich.value = 'import';
}

/** 自检操作 */
function handleCheck() {
  const _ids = ids.value;
  proxy.$modal.confirm('是否确认自检这' + _ids.length + '项？').then(() => {
    request({
      url: '/comlbs/equipmentManagement/selfCheck',
      method: 'post',
      data: {
        ids: ids.value
      }
    }).then(res => {
      getList();
      proxy.$modal.msgSuccess("自检成功");
    })
  })
}

/** 转移操作 */
function handleSwitch() {
  open.value = true;
  title.value = "转移数据";
  showWhich.value = 'switch';
}

/** 提交按钮 */
async function submitForm() {
  let _bool = await formInfo.value.validate();
  if (!_bool) return
  let _updateInfo = formInfo.value.updateInfo
  switch (showWhich.value) {
    case "import":
      let formData = new FormData();
      formData.append('file', _updateInfo.file);
      formData.set('companyId', _updateInfo.companyId);
      let loadingInstance = ElLoading.service({ text: "正在导入数据，请稍候", background: "rgba(0, 0, 0, 0.7)", })
      request({
        url: '/comlbs/equipmentManagement/importData',
        method: 'post',
        data: formData
      }).then(res => {
        proxy.$modal.msgSuccess("导入成功");
        open.value = false;
        getList();
        loadingInstance.close();
      }).catch(() => {
        loadingInstance.close();
      })
      break;
    case "switch":
      _updateInfo.ids = ids.value;
      request({
        url: '/comlbs/equipmentManagement/batchUpdateCompany',
        method: 'post',
        data: _updateInfo
      }).then(res => {
        proxy.$modal.msgSuccess("转移成功");
        open.value = false;
        getList();
      })
      break;
    default:
      let supervisionInfo = formInfo.value.supervisionInfo
      let driverInfo = formInfo.value.driverInfo
      let myUploadPic = formInfo.value.myUploadPic
      let driverUploadPic = formInfo.value.driverUploadPic
      // 不选监管类型时，将监管信息置空
      if (!_updateInfo.objType && _updateInfo.objType !== 0) {
        supervisionInfo = {}
        driverInfo = {}
      }
      let data = {
        deviceId: _updateInfo.deviceId,
        companyId: _updateInfo.companyId,
        deviceModel: _updateInfo.deviceModel,
        simId: _updateInfo.simId ?? '',
        objType: _updateInfo.objType,
        channels: '', // 视频接入
        remark: _updateInfo.remark,
        objIcon: formInfo.value.activeImg, // 设备图标
        numberPlate: supervisionInfo.numberPlate?.numberPlate || supervisionInfo.numberPlate,
        vehicleColor: supervisionInfo.vehicleColor,
        vehiclePic: [],  // 图片附件
        vehicleModel: supervisionInfo.vehicleModel,
        vehicleId: supervisionInfo.vehicleId,
        ageVehicle: supervisionInfo.objAge,
        objSex: supervisionInfo.objSex,
        contactNumberVehicle: supervisionInfo.objContactNumber,
        equipmentId: _updateInfo?.equipmentId,
        driverId: driverInfo.driverId, // 负责人id
        driverName: driverInfo.name?.name || driverInfo.name, // 负责人
        contactNumber: driverInfo.contactNumber,
        idCard: driverInfo.idCard, // 身份证号
        age: driverInfo.age,
        driverPic: [],  // 负责人图片附件
      }
      let channelArr = []
      if (_updateInfo.channels) {
        for (let i = 0; i < _updateInfo.channels; i++) {
          // 0表示没有选
          channelArr.push(sel_option.value.channels[i].chVal ?? 0)
        }
      }
      data.channels = channelArr.join(',')

      // 监管对象的图片附件
      data.vehiclePic = await myUploadPic?.[0]?.uploadInfo();
      // 负责人的图片附件
      data.driverPic = await driverUploadPic?.[0]?.uploadInfo();
      if ((_updateInfo.objType || _updateInfo.objType === 0) && !data.objIcon) {  // 选监管类型时，设备图标必选
        proxy.$modal.msgWarning("请选择设备图标！");
        return
      }
      if (data.equipmentId != null) {
        updateEquipmentManagement(data).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addEquipmentManagement(data).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
      break;
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.equipmentId || ids.value;
  const _length = row.equipmentId ? 1 : _ids.length
  proxy.$modal.confirm('是否确认删除这' + _length + '项？').then(function () {
    return delEquipmentManagement(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comlbs/equipmentManagement/export', {
    ...queryParams.value
  }, `设备管理_${dayjs(new Date()).format("YYYY-MM-DD_HH:mm:ss")}.xlsx`)
}

// 下发
function handleIssue(row) {
  queryIssue.value = row
  queryIssue.value.name = ''
  queryIssueTime.value = []
  issueOpen.value = true;
  activeName.value = 'first'
  getIssueTableData(row.id)
}
function tabChangeIssue(name) {
  if (name == 'second') {
    getIssueRecordData()
  }
}
function getIssueTableData() {
  let data = {
    vehicleId: queryIssue.value.vehicleId ?? -1, //当设备没绑定监管对象时(即vehicleId为null),传-1
    companyId: queryIssue.value.companyId,
    deviceId: queryIssue.value.deviceId,
    name: queryIssue.value.name,
    onlyBind: 1
  }
  request({
    url: "/comlbs/driverInfo/list",
    method: "get",
    params: data
  }).then(res => {
    if (res.code == 200) {
      tableIssueData.value = res.rows
    }
  })
}
function handleIssueSelectionChange(val) {
  multipleIssueSelection = val
}
function handIssueSubmit() {
  if (multipleIssueSelection.length == 0) {
    proxy.$modal.msgError("下发不能为空！")
    return
  }
  let list = []
  multipleIssueSelection.forEach(v => {
    list.push({ idCard: v.idCard, facePictureUrl: v.picture.length > 0 ? v.picture[0].path : '', driverName: v.name, driverId: v.id })
  });
  let data = {
    deviceId: queryIssue.value.deviceId,
    list: list
  }
  request({
    url: "/comlbs/driverInfo/sendFace",
    method: "post",
    data: data
  }).then(res => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess("下发成功!");
      handleClose()
    }
  })
}
function handleClose() {
  issueOpen.value = false;
}
function getIssueRecordData() {
  let data = {
    vehicleId: queryIssue.value.vehicleId ?? -1, //当设备没绑定监管对象时(即vehicleId为null),传-1
    startTime: queryIssueTime.value ? queryIssueTime.value[0] : '',
    endTime: queryIssueTime.value ? queryIssueTime.value[1] : ''
  }
  request({
    url: "/comlbs/driverInfo/driverFaceSendRecord",
    method: "post",
    data: data
  }).then(res => {
    if (res.code == 200) {
      issueRecordData.value = res.data
    }
  })
}

getList();
</script>
<style lang="scss" scoped>
.issue-dom {
  margin-top: 15px;
  height: calc(100% - 60px);
}

.unsetSearch {
  display: flex;
  height: 34px;
  align-items: center;

  .search-input {
    width: 214px;
    margin-right: 20px;
  }

  .search-btn {
    margin-left: 20px;
  }
}

.dialog-table {
  margin-top: 20px;
  height: calc(100% - 110px);
}

.dialog-footer {
  text-align: right;
}
</style>